package com.anntly.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * @Auther: 张文
 * @Date: 2020/6/14 19:03
 * @Description:
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    Random random = new Random();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) throws Exception {
        String content = new String(messageProtocol.getContent(), CharsetUtil.UTF_8);
        System.out.println("收到消息:"+content);
        // 回复消息
        String result = String.valueOf(random.nextInt(100));
        byte[] resultContent = result.getBytes(CharsetUtil.UTF_8);
        MessageProtocol res = new MessageProtocol();
        res.setLen(resultContent.length);
        res.setContent(resultContent);
        channelHandlerContext.writeAndFlush(res);
    }
}
